package com.nintendo.bubblechat.utils;

import com.nintendo.bubblechat.config.MinioConfig;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Component
public class MinioUtils {
//    @Autowired
    private MinioConfig minioConfig;

    public MinioUtils(MinioConfig minioConfig) {
        this.minioConfig = minioConfig;
    }

    /**
     * 文件上传 将文件传到minio中
     *
     * @param file
     */
    public String upload(MultipartFile file) throws Exception {
        try {
            // 创建客户端对象
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint("http://" + minioConfig.getEndpoint() + ":" + minioConfig.getPort())
                            .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                            .build();

            // Make 'asiatrip' bucket if not exist.
            // 准备
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucketName()).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConfig.getBucketName()).build());
            } else {
                System.out.println("Bucket 'asiatrip' already exists.");
            }
            // 构建对象名称 避免文件名称重复
            // Upload known sized input stream.
            // Upload known sized input stream.
            String originalFilename = file.getOriginalFilename();
            String extName = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            } else {
                // 如果文件名中没有扩展名，默认使用空字符串或其他默认值
                extName = ".png";  // 或者你可以选择其他默认扩展名，例如 ".unknown"
            }
            String objectName = UUID.randomUUID().toString() + extName;
            String folderName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/"));
            objectName = folderName + objectName;
            // 文件上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioConfig.getBucketName())
                            .object(objectName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            System.out.println(
                    "'/home/user/Photos/asiaphotos.zip' is successfully uploaded as "
                            + "object 'asiaphotos-2015.zip' to bucket 'asiatrip'.");
            return minioConfig.getBucketName()+"/"+objectName;

        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        }
        return null;
    }
}
